import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Modal, message, Spin } from 'antd';
import Cropper from 'react-cropper';
import 'cropperjs/dist/cropper.css';
import ImgCropper from './ImgCropper.js';
import styles from './imgCropper.less'

const mapState = (state) => {
  let { visible, src, width, height, picWidth, picHeight, cropperKey } = state.album.cropperModal
  return { visible, src, width, height, picWidth, picHeight, cropperKey }
}
@connect(mapState)


export default class CropperModal extends PureComponent {
  state = {
    dataUrl: '',
    nicaiCrx: null,
    version: '',
    confirmLoading: false,
    outputWidth: 0,
    outputHeight: 0,
    setCropData: true,
    frameWidth: 500,
    frameHeight: 360,
    loading: false,
    timeout: null,
  }
  componentDidMount() {
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.k === nextProps.cropperKey) {
      if (!this.props.visible && nextProps.visible) {
        const nicaiCrx = document.getElementById('nicaiCrx');
        nicaiCrx.addEventListener('uploadResult', this.uploadResult);
        nicaiCrx.addEventListener('setVersion', this.setVersion);
        if (!this.state.nicaiCrx) {
          this.setState({ nicaiCrx }, () => {
            setTimeout(() => {
              this.handleGetVersion();
            }, 600);
          });
        }
        const timeout = setTimeout(() => {
          if(!this.state.version){
            message.destroy();
            message.warn('请安装尼采创作平台插件！CropperModal', 60 * 60);
            this.setState({ loading: false });
          }
        }, 5000);
        this.setState({
          loading: true,
          timeout,
        });
      } else if (this.props.visible && !nextProps.visible) {
        const { nicaiCrx } = this.state;
        nicaiCrx.removeEventListener('uploadResult', this.uploadResult);
        this.setState({
          nicaiCrx: null,
          setCropData: true,
        });
        if (this.state.timeout) {
          clearTimeout(this.state.timeout);
        }
      }
    }
  }
  setVersion = (e) => {
    const data = JSON.parse(e.target.innerText);
    if (data.error) {
      message.warn(data.msg);
    }
    this.setState({
      version: data.version,
    });
    this.state.nicaiCrx.removeEventListener('setVersion', this.setVersion);
  }
  uploadResult = (e) => {
    const result = JSON.parse(e.target.innerText);
    if (!result.errorCode && result.data.length > 0) {
      this.setState({ confirmLoading: false });
      message.destroy();
      message.success('上传成功');
      if (this.props.onOk) {
        this.props.onOk({
          materialId: result.data[0].materialId,
          picWidth: result.data[0].picWidth,
          picHeight: result.data[0].picHeight,
          url: result.data[0].url,
        });
      }
      this.setState({ dataUrl: '' });
      this.props.dispatch({
        type: 'album/hideCropper',
      });
    } else {
      message.error(result.message);
    }
  }
  handleGetVersion = () => {
    const customEvent = document.createEvent('Event');
    customEvent.initEvent('getVersion', true, true);
    this.state.nicaiCrx.dispatchEvent(customEvent);
  }
  handledataURLtoBlob = (dataurl) => {
    const arr = dataurl.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n >= 0) {
      u8arr[n] = bstr.charCodeAt(n);
      n--;
    }
    return new Blob([u8arr], {
      type: mime
    });
  }
  handleOk = async () => {
    this.setState({ confirmLoading: true });
    const dataUrl = await this.imgCropper.save(this.props.src, 500);
    this.handleSubmit(dataUrl)
  }
  handleSubmit = (url) => {
    this.state.nicaiCrx.innerText = JSON.stringify({ data: url });
    const customEvent = document.createEvent('Event');
    customEvent.initEvent('uploadImg', true, true);
    this.state.nicaiCrx.dispatchEvent(customEvent);
    message.destroy();
    message.loading('上传中 ...', 60 * 60);
  }
  handleCancel = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'album/hideCropper',
    });
    message.destroy();
    this.setState({ dataUrl: '', confirmLoading: false });
  }
  render() {
    const { visible, src, k, cropperKey, width, height } = this.props;
    const { confirmLoading } = this.state;
    const flag = k === cropperKey && visible;
    return (
      <Modal
        title="裁切"
        width="680px"
        visible={flag}
        onOk={this.handleOk}
        onCancel={this.handleCancel}
        bodyStyle={{ padding: '5px 20px' }}
        maskClosable={false}
        confirmLoading={confirmLoading}
      >
          <ImgCropper ref={(imgCropper) => { this.imgCropper = imgCropper}}
            src={src}
            minImageHeight={height}
            minImageWidth={width}
            visible= {visible}
          ></ImgCropper>
      </Modal>
    );
  }
}
